<template>
  <div class="main_box" style="padding: 10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ $route.query.id ? '修 改 医 检 项 目 组 信 息' : '新 增 医 检 项 目 组' }}</h2>
        <div>
          <el-tooltip class="item" effect="dark" content="关联医检项目可多选" placement="top-end">
            <i class="el-icon-info"></i>
          </el-tooltip>
          <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList(0)"> 返 回</el-button>
        </div>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules" style="margin: 0">
        <el-row>
          <el-form-item label="项目组名称" prop="itemName" style="width: 100%">
            <el-input v-model="dataForm.itemName" style="width: 100%" clearable show-word-limit @blur="listReportItem(dataForm.itemName)"></el-input>
          </el-form-item>
          <el-form-item label="项目组别称" prop="itemShortName" style="width: 100%">
            <el-input v-model="dataForm.itemShortName" style="width: 100%" clearable show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="项目组编号" prop="itemCode">
            <el-input v-model="dataForm.itemCode" clearable show-word-limit></el-input>
          </el-form-item>
          <InstitutionSelect @institutionId="getInstitutionId" :id="dataForm.institutionId" :site="1" :disabled="modifyDisabled"> </InstitutionSelect>
          <el-form-item label="检验科室名称" prop="itemGroup">
            <el-input v-model="dataForm.itemGroup" clearable show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="检验科室编号" prop="itemGroupCode">
            <el-input v-model="dataForm.itemGroupCode" clearable show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="检测日期" prop="itemDate">
            <el-date-picker v-model="dataForm.itemDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" clearable> </el-date-picker>
            <!-- <el-input v-model="dataForm.itemDate" clearable>
              </el-input> -->
          </el-form-item>
          <el-form-item label="检测时长" prop="itemTime">
            <el-input v-model="dataForm.itemTime" clearable>
              <template slot="append">小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="原价格" prop="itemPrice">
            <el-input v-model="dataForm.itemPrice" type="number" step="0.01">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="采样耗材自供" prop="collectSelf">
            <el-switch v-model="dataForm.collectSelf" active-color="#13ce66" active-value="1" inactive-value="0"> </el-switch>
          </el-form-item>
          <el-form-item label="合作价格" prop="itemSalePrice">
            <el-input v-model="dataForm.itemSalePrice" type="number">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="方法学" prop="methodology">
            <el-select v-model="dataForm.methodology" filterable clearable placeholder="请选择方法学">
              <el-option v-for="item in methodologyList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 当是新增时 -->
          <div v-if="!$route.query.id">
            <el-form-item label="关联康来项目组" prop="reportItemId">
              <el-select v-model="dataForm.reportItemId" filterable placeholder="请选择康来项目组" :loading="loadingIns">
                <el-option v-for="item in pickReportItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>

            <!-- 关联子菜单 -->
            <el-col :span="24">
              <el-form-item label="快速关联医检项目组" prop="itemIdList" style="width: 100%">
                <el-select v-model="dataForm.itemIdList" multiple filterable style="width: 100%" placeholder="请选择医检项目组" :loading="loadingIns" :disabled="modifyDisabled">
                  <el-option v-for="item in pickItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="关联医检(子)项目" prop="subItemIdList" style="width: 100%">
                <el-select v-model="dataForm.subItemIdList" multiple filterable style="width: 100%" placeholder="请选择医检子项目" :loading="loadingIns">
                  <el-option v-for="item in pickSubItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </div>
          <el-col :span="24">
            <el-form-item label="采样要求" prop="collectRequire" style="width: 100%">
              <el-input type="textarea" v-model="dataForm.collectRequire" autosize placeholder="请输入采样要求"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="临床意义" prop="itemMeaning" style="width: 100%">
              <el-input type="textarea" v-model="dataForm.itemMeaning" autosize placeholder="请输入临床意义"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注意事项" prop="itemNote" style="width: 100%">
              <el-input type="textarea" v-model="dataForm.itemNote" autosize placeholder="请输入注意事项"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark" clearable style="width: 100%">
              <el-input type="textarea" autosize="" v-model="dataForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表单保存和提交 -->
        <el-row>
          <el-form-item>
            <el-button type="primary" @click="sureDrugClick">{{$route.query.id?'保 存 基 本 信 息':'保 存'}}</el-button>
            <el-button @click="returnList(0)">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <!-- 编辑 -->
      <div v-if="$route.query.id">
        <div class="tit">
          <h2>修 改 关 联 信 息</h2>
        </div>
        <el-form label-width="200px" style="margin: auto 0">
          <el-row>
            <el-form-item label="关联康来项目组" prop="reportItemId">
              <el-select v-model="dataForm.reportItemId" filterable placeholder="请选择康来项目组" :loading="loadingIns">
                <el-option v-for="item in pickReportItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联医检(子)项目" prop="subItemIdList" style="width: 100%">
              <el-select v-model="dataForm.subItemIdList" multiple filterable style="width: 100%" placeholder="请选择医检子项目" :loading="loadingIns">
                <el-option v-for="item in pickSubItemIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-row>

          <!-- 表单保存和提交 -->
          <el-row>
            <el-form-item>
              <el-button type="primary" @click="sureSubmit">保 存 关 联 信 息</el-button>
              <el-button @click="returnList">取 消</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import * as validators from '@/utils/validators';
import * as message from '@/constants/message';
import InstitutionSelect from '@/components/InstitutionSelect';
import InstitutionItemApi from '@/api/institution/institutionItem';
import ReportItemApi from '@/api/report/reportItem';

export default {
  data() {
    return {
      roleRules: {
        itemName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur',
          },
        ],
        institutionId: [
          {
            required: true,
            message: '请选择对应医检',
            trigger: 'change',
          },
        ],
      },
      loadingIns: false,
      modifyDisabled: false,
      dataForm: {
        // 表单数据
        itemId: '',
        itemCode: '',
        itemName: '',
        itemShortName: '',
        klItemName: '',
        institutionId: '',
        itemDate: '',
        itemTime: '',
        itemGroup: '',
        itemGroupCode: '',
        itemPrice: '',
        itemSalePrice: '',
        collectSelf: 0, // 默认不自供采样耗材
        collectRequire: '',
        itemMeaning: '',
        itemNote: '',
        reportItemId: '', // 选中后的报告单项目id
        subItemIdList: [], // 选中后的机构子项目列表
        itemIdList: [], // 选中后的机构项目列表
        methodology: '',
        remark: '',
      },
      pickSubItemIdList: [], // 所有机构子项目列表
      pickItemIdList: [], // 所有机构项目组列表
      pickReportItemIdList: [], // 所有报告单项目组列表
      methodologyList: [
        { id: '化学发光学', name: '化学发光学' },
        { id: '胶体金法', name: '胶体金法' },
        { id: '其它', name: '其它' },
      ],
    };
  },
  components: {
    InstitutionSelect,
  },
  mounted() {
    this.init();
    if(this.$route.query.institutionId){
      this.dataForm.institutionId = this.$route.query.institutionId
      this.getInstitutionId(this.dataForm.institutionId)
    }
  },
  methods: {
    init() {
      let _this = this;

      // _this.listReportItem();
      this.$Utils.clearData(_this.dataForm);
      if (this.$route.query.id) {
        _this.dataForm.itemId = parseInt(_this.$route.query.id);
        _this.getData();

      }
    },
    sureSubmit() {
      this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
        this.editData(true);
      });
    },
    sureDrugClick() {
      // 提交
      let _this = this;
      _this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.dataForm.itemId) {
            //做一个基础的判断，id不为空就编辑，id为空就增加
            this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
              this.editData();
            });
          } else {
            //  if(this.dataForm.subItemIdList.length<1&&this.dataForm.itemIdList.length<1){
            //     this.$message('医检项目组或者医检子项目必须选一个');
            //     return
            //   }
            this.$confirm(message.MSG_CONFIRM_SAVE_ADD, message.TITLE_PROMPT, {}).then(() => {
              this.addData();
            });
          }
        }
      });
    },
    addData() {
      let _this = this; //限制作用域

      let cond = {
        // 表单数据
        // itemId: _this.dataForm.itemId,
        itemName: _this.dataForm.itemName,
        itemShortName: _this.dataForm.itemShortName,
        itemCode: _this.dataForm.itemCode,
        itemGroup: _this.dataForm.itemGroup,
        itemGroupCode: _this.dataForm.itemGroupCode,
        klItemName: _this.dataForm.klItemName,
        institutionId: _this.dataForm.institutionId,
        reportItemId: _this.dataForm.reportItemId, //关联报告单项目
        subItemIdList: _this.dataForm.subItemIdList, //关联多个机构子项目
        itemIdList: _this.dataForm.itemIdList, //关联多个机构项目组
        itemDate: _this.dataForm.itemDate,
        itemTime: _this.dataForm.itemTime,
        itemPrice: _this.dataForm.itemPrice,
        itemSalePrice: _this.dataForm.itemSalePrice,
        collectSelf: _this.dataForm.collectSelf,
        collectRequire: _this.dataForm.collectRequire,
        itemMeaning: _this.dataForm.itemMeaning,
        itemNote: _this.dataForm.itemNote,
        methodology: _this.dataForm.methodology,
        remark: _this.dataForm.remark,
      };
      InstitutionItemApi.addInstitutionItem(cond).then((data) => {
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS,
        });
        this.returnList(cond);
      });
    },
    editData(flag = false) {
      // 编辑
      let _this = this;
      let cond = {
        // 表单数据
        itemId: _this.dataForm.itemId,
        itemName: _this.dataForm.itemName,
        itemShortName: _this.dataForm.itemShortName,
        itemCode: _this.dataForm.itemCode,
        itemGroup: _this.dataForm.itemGroup,
        itemGroupCode: _this.dataForm.itemGroupCode,
        institutionId: _this.dataForm.institutionId,
        reportItemId: _this.dataForm.reportItemId, //关联报告单项目
        subItemIdList: _this.dataForm.subItemIdList, //关联多个子项目
        // itemIdList: _this.dataForm.itemIdList,  //关联多个机构项目组
        itemDate: _this.dataForm.itemDate,
        itemTime: _this.dataForm.itemTime,
        itemPrice: _this.dataForm.itemPrice,
        itemSalePrice: _this.dataForm.itemSalePrice,
        collectSelf: _this.dataForm.collectSelf,
        collectRequire: _this.dataForm.collectRequire,
        itemMeaning: _this.dataForm.itemMeaning,
        itemNote: _this.dataForm.itemNote,
        methodology: _this.dataForm.methodology,
        remark: _this.dataForm.remark,
      };
      if (flag) {
        cond.update = 2;
      }
      InstitutionItemApi.editInstitutionItem(cond)
        .then((data) => {
          this.$notify.success({
            title: message.TITLE_SUCCESS,
            message: message.MSG_ACTION_SUCCESS,
          });
          this.returnList(cond);
        })
        .catch((error) => {
          if (error.msg) {
            this.$message.error(message.MSG_ACTION_FAIL);
          }
        });
    },
    getData() {
      // 编辑前，获取数据
      let _this = this;
      _this.modifyDisabled = true;
      InstitutionItemApi.getInstitutionItem({
        itemId: this.$route.query.id,
      }).then((res) => {
        this.$Utils.bindingBean(this.dataForm, res.data);

        if (res.data.reportItemId) {
          this.dataForm.reportItemId = parseInt(res.data.reportItemId);
        }
        if (res.data.collectSelf) {
          this.dataForm.collectSelf = parseInt(res.data.collectSelf);
        }
        if (res.data.institutionId) {
          this.dataForm.institutionId = parseInt(res.data.institutionId);
        }
        this.dataForm.subItemIdList = res.data.subItemIdList;
        this.listInstitutionSubItem(res.data.institutionId);
        _this.listReportItem(this.dataForm.itemName);
      });
    },
    listReportItem(name) {
      // 获取报告单项目组列表
      if(!name){
        return false
      }
      let _this = this;
      let cond = {
        query:1,
        name
      };
      _this.loadingIns = true;
      ReportItemApi.getReportItemsNameList(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.pickReportItemIdList = res.data.map((item) => {
            return {
              value: item.itemId,
              label: item.itemName,
            };
          });
        }, 200);
      });
    },
    // 获取机构子项目列表
    listInstitutionSubItem(val) {
      let _this = this;
      let cond = {
        institutionId: String(val),
        state: 1,
      };
      _this.loadingIns = true;
      InstitutionItemApi.listSubInstitutionItems(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickSubItemIdList = res.data.map((item) => {
              return {
                value: item.subItemId,
                label: item.subItemName + ' (' + item.subItemGroup + '-' + item.subItemCode + ')',
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickSubItemIdList = [];
          console.error(error);
        });
    },
    // 获取机构项目组列表
    listItemIdList(val) {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        institutionId: String(val),
      };
      InstitutionItemApi.listInstitutionItems(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickItemIdList = res.data.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickItemIdList = [];
          console.error(error);
        });
    },
    getInstitutionId(val) {
      // 清空选择的关联机构和子机构
      (this.dataForm.subItemIdList = []), // 选中后的机构子项目列表
        (this.dataForm.itemIdList = []); // 选中后的机构项目列表
      // 将组件中的id 附给搜索的按钮
      this.dataForm.institutionId = String(val);
      this.pickItemIdList = []; //当id发生变化、清空数组重新加载
      this.listItemIdList(val); // 机构id发生变化，根据id查找项目组列表
      this.pickSubItemIdList = [];
      this.listInstitutionSubItem(val);
    },
    returnList(val) {
      let _this = this;
      if (val) {
        this.$store.dispatch('delView', this.$route);
        _this.$router.push({
          path: '/items/institutionItemManagement',
          query: { id: val.institutionId },
        });
      } else {
        this.$store.dispatch('delView', this.$route);
        this.$router.push({ path: '/items/institutionItemManagement' });
        // _this.$router.go(-1);
      }
    },
  },
};
</script>

<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
